package org.raymond.iworks.study.app;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.raymond.iworks.core.constants.SecurityComponets;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
@Slf4j
public class LoginTest {
    private RSA rsa = SecurityComponets.DEFAULT_ENCRYPTOR;
    private static String key = "abcdefghijklmnop";
    private static String iv = "0987654321012345";
    private static AES aes;

    @Test
    public void test0(){
        // 支持postman调用login接口,加密请求参数
        // rsa publicKey每次重启会变,需要重新从common/config/system接口获取一次
        // 注意key和iv的长度
        String publicKeyBase64 = rsa.getPublicKeyBase64();
        log.info("publicKeyBase64:{}", publicKeyBase64);
        String keyEncoded = rsa.encryptBase64(key, CharsetUtil.CHARSET_UTF_8, KeyType.PublicKey);
        String ivEncoded = rsa.encryptBase64(iv, CharsetUtil.CHARSET_UTF_8, KeyType.PublicKey);
        log.info("keye:{}", keyEncoded);
        log.info("ive:{}", ivEncoded);

        Map<String, Object> loginParam = new HashMap<>();
        loginParam.put("username", "diablo01");
        loginParam.put("password", "Diablo01@");
        String loginStr = JSONUtil.toJsonStr(loginParam);
        aes = new AES("CBC", "PKCS7Padding", key.getBytes(StandardCharsets.UTF_8), iv.getBytes(StandardCharsets.UTF_8));

        // 使用aes加密,base64编码的字符串作为请求参数
        String encrypted = aes.encryptBase64(loginStr, CharsetUtil.CHARSET_UTF_8);
        log.info("original:{}, encrypt&base64:{}", loginStr, encrypted);
    }
}
